use std::{collections::HashMap, path::Path};

use serde::de::DeserializeOwned;

pub fn converter(input: &str) -> String {
    // 资源文件源自 pypinyin
    let pinyin: HashMap<char, String> = load_json("pinyin_dict.json");
    let phrases: HashMap<String, Vec<String>> = load_json("phrases_dict.json");

    let out = if let Some(val) = phrases.get(input) {
        val.join(" ")
    } else {
        input
            .chars()
            .flat_map(|x| pinyin.get(&x).cloned())
            .collect::<Vec<_>>()
            .join(" ")
    };

    uppercase_first(&out)
}

pub fn load_json<T: DeserializeOwned>(path: impl AsRef<Path>) -> T {
    let data = std::fs::read(path).unwrap();
    serde_json::from_slice(&data).unwrap()
}

pub fn uppercase_first(input: &str) -> String {
    let mut flag = true;
    input
        .chars()
        .map(|x| {
            if flag {
                flag = false;
                x.to_ascii_uppercase()
            } else {
                x
            }
        })
        .collect()
}
